using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DocumentChunksController : ControllerBase
    {
        private readonly IDocumentChunkService _documentChunkService;

        public DocumentChunksController(IDocumentChunkService documentChunkService)
        {
            _documentChunkService = documentChunkService;
        }

        /// <summary>
        /// 获取所有文档分片
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<DocumentChunk>>> GetAllDocumentChunks()
        {
            var chunks = await _documentChunkService.GetAllAsync();
            return Ok(chunks);
        }

        /// <summary>
        /// 根据ID获取文档分片
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<DocumentChunk>> GetDocumentChunk(Guid id)
        {
            var chunk = await _documentChunkService.GetByIdAsync(id);
            if (chunk == null)
            {
                return NotFound($"文档分片 {id} 不存在");
            }
            return Ok(chunk);
        }

        /// <summary>
        /// 根据文档ID获取所有分片
        /// </summary>
        [HttpGet("document/{documentId}")]
        public async Task<ActionResult<IEnumerable<DocumentChunk>>> GetChunksByDocument(Guid documentId)
        {
            var chunks = await _documentChunkService.GetByDocumentIdAsync(documentId);
            return Ok(chunks);
        }

        /// <summary>
        /// 根据文档ID和索引范围获取分片
        /// </summary>
        [HttpGet("document/{documentId}/range")]
        public async Task<ActionResult<IEnumerable<DocumentChunk>>> GetChunksByRange(
            Guid documentId, 
            [FromQuery] int startIndex, 
            [FromQuery] int endIndex)
        {
            var chunks = await _documentChunkService.GetChunksByRangeAsync(documentId, startIndex, endIndex);
            return Ok(chunks);
        }

        /// <summary>
        /// 创建新的文档分片
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<DocumentChunk>> CreateDocumentChunk([FromBody] CreateDocumentChunkRequest request)
        {
            try
            {
                var chunk = await _documentChunkService.CreateAsync(
                    request.DocumentId, 
                    request.ChunkIndex, 
                    request.Content, 
                    request.Vector);
                return CreatedAtAction(nameof(GetDocumentChunk), new { id = chunk.Id }, chunk);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建文档分片失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量创建文档分片
        /// </summary>
        [HttpPost("batch")]
        public async Task<IActionResult> BatchCreateDocumentChunks([FromBody] List<DocumentChunk> chunks)
        {
            try
            {
                await _documentChunkService.BatchCreateAsync(chunks);
                return Ok($"成功创建 {chunks.Count} 个文档分片");
            }
            catch (Exception ex)
            {
                return BadRequest($"批量创建文档分片失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新文档分片
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateDocumentChunk(Guid id, [FromBody] DocumentChunk chunk)
        {
            if (id != chunk.Id)
            {
                return BadRequest("文档分片ID不匹配");
            }

            try
            {
                await _documentChunkService.UpdateAsync(chunk);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新文档分片失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除文档分片
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteDocumentChunk(Guid id)
        {
            try
            {
                await _documentChunkService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除文档分片失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除指定文档的所有分片
        /// </summary>
        [HttpDelete("document/{documentId}")]
        public async Task<IActionResult> DeleteChunksByDocument(Guid documentId)
        {
            try
            {
                await _documentChunkService.DeleteByDocumentIdAsync(documentId);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除文档分片失败: {ex.Message}");
            }
        }
    }

    // 请求模型
    public class CreateDocumentChunkRequest
    {
        public Guid DocumentId { get; set; }
        public int ChunkIndex { get; set; }
        public string Content { get; set; } = string.Empty;
        public float[] Vector { get; set; } = Array.Empty<float>();
    }
}
